<template>
  <div :class="$style.msgLog">
    <ContentWrap>
      <FormContainer :column="3">
        <el-form ref="form" :model="formData" :rules="formRules" label-width="80px">
          <el-form-item prop="phone" label="手机号">
            <el-input v-model.trim="formData.phone" placeholder="请输入手机号" clearable />
          </el-form-item>
          <el-form-item prop="state" label="发送状态">
            <el-select v-model="formData.state" placeholder="请选择发送状态" clearable filterable>
              <el-option label="保存" value="0" />
              <el-option label="未发送" value="1" />
              <el-option label="已发送" value="2" />
              <el-option label="发送失败" value="3" />
            </el-select>
          </el-form-item>
          <el-form-item prop="sendDate" label="发送时间">
            <el-date-picker v-model="formData.sendDate" opt type="daterange" start-placeholder="开始时间" end-placeholder="结束时间" clearable />
          </el-form-item>
          <el-form-item prop="group" label="业务组">
            <el-select v-model="formData.group" placeholder="请选择业务组" clearable filterable @change="changeHandle">
              <el-option v-for="(ag,i) in groupList" :key="i" :label="ag.groupName" :value="ag.groupNo" />
            </el-select>
          </el-form-item>
          <el-form-item prop="sender" label="发送坐席">
            <el-select v-model="formData.sender" placeholder="请选择业务组后再选择发送坐席" remote :remote-method="remoteSearch" :disabled="formData.group===''" clearable filterable>
              <el-option v-for="al in agentList" :key="al.staffCode" :label="`${al.staffName}(${al.accountNo})`" :value="al.accountNo" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <Button type="primary" :loading="loading" enter @click="queryHandle">查询</Button>
          </el-form-item>
        </el-form>
      </FormContainer>
      <ExportPane :data-source="selectedArry" :table-config="tableConfig" :query-data-fun="queryHandle" filename="短信发送记录">导出</ExportPane>
      <table-box ref="table" no-request show-selection :table-config="tableConfig" :other-filters="otherFilters" @selection-change="handleSelectionChange" />
    </ContentWrap>
  </div>
</template>
<script>
import ContentWrap from '@/components/ContentWrap'
import Button from '@/components/Button'
import FormContainer from '@/components/FormContainer'
// import { validatPhone } from '@/utils/validate'
import { notEmpty, filtersRaw, pageRequsetBody, parseTime, date24 } from '@/utils'
// import { getBusinessAll } from '@/api/business'
// import { getBusinessMembers } from '@/api/staffInfo'
import { getBusinessMembers } from '@/api/business'
import { mapGetters } from 'vuex'
import ExportPane from '@/components/ExportPane'
export default {
  name: 'SMSSendLog',
  components: {
    ContentWrap,
    FormContainer,
    Button,
    ExportPane
  },
  data() {
    // 验证手机号
    // const validatorPhone = (r, v, c) => {
    //   if (notEmpty(v)) {
    //     validatPhone(v) ? c() : c(new Error('电话号码格式不正确'))
    //   } else {
    //     c()
    //   }
    // }
    return {
      // 业务组
      agentOrgList: [],
      // 坐席列表
      agentList: [],
      // 额外筛选条件
      otherFilters: [],
      formData: {
        phone: '',
        state: '',
        sendDate: [],
        sender: '',
        group: ''
      },
      formRules: {
        // phone: [{ validator: validatorPhone, trigger: 'change' }]
      },
      loading: false,
      tableConfig: {
        interfacePath: '/call-center/api/v1/smsSendRecord/page',
        pageFlag: true,
        hideFuncBar: true,
        sort: 'sendDate',
        order: 'desc',
        // 表格字段动态配置
        setting: [
          {
            prop: 'senderName',
            label: '发送坐席',
            formatData: v => `${v.senderName}(${v.sender})`
          },
          {
            prop: 'phone',
            label: '手机号码'
          },
          {
            prop: 'content',
            label: '短信内容'
          },
          {
            prop: 'sendDate',
            label: '发送时间'
          },
          {
            prop: 'state',
            label: '发送状态',
            formatData(v) {
              // 0保存1未发送2：已发送 3:发送失败
              let t = ''
              const state = v.state
              if (state === 0 || state === '0') {
                t = '保存'
              } else if (state === 1 || state === '1') {
                t = '未发送'
              } else if (state === 2 || state === '2') {
                t = '已发送'
              } else if (state === 3 || state === '3') {
                t = '发送失败'
              }
              return t
            }
          }
        ]
      },
      selectedArry: []
    }
  },
  computed: {
    ...mapGetters(['groupList'])
  },
  created() {
    // this.getBusinessAll()
    this.remoteSearch('')
  },
  methods: {
    handleSelectionChange(rows) {
      this.selectedArry = rows
    },
    // 组织改变
    changeHandle() {
      this.$set(this.formData, 'sender', '')
      this.remoteSearch('')
    },
    // 查询
    queryHandle(type) {
      this.loading = true
      // "content": "string",
      // "deptCode": "string",
      // "id": "string",
      // "isTiming": 0,
      // "group": "string",
      // "phone": "string",
      // "sendDate": "2020-08-11T01:08:58.314Z",
      // "sender": "string",
      // "state": 0
      const t = []
      this.formData.sendDate ? '' : this.formData.sendDate = []
      if (this.formData.sendDate.length > 1) {
        t.push(
          filtersRaw('sendDate', parseTime(this.formData.sendDate[0]), '>'),
          filtersRaw('sendDate', parseTime(date24(this.formData.sendDate[1])), '<=')
        )
      }
      let v = this.formData.group
      if (!notEmpty(v)) {
        v = this.groupList.map(e => e.groupNo).join(',')
      }
      t.push(filtersRaw('group', v, 'in'))
      if (notEmpty(this.formData.state)) {
        t.push(filtersRaw('state', this.formData.state, '='))
      }
      v = this.formData.sender
      if (notEmpty(v)) {
        t.push(filtersRaw('sender', v, '='))
      }
      v = this.formData.phone
      if (notEmpty(v)) {
        t.push(filtersRaw('phone', this.formData.phone, 'like'))
      }
      this.otherFilters = t
      return this.$refs.form.validate().then(() => {
        this.loading = false
        if (type !== 'export') {
          this.$nextTick(() => {
            this.$refs.table.initTableData()
          })
        } else {
          return this.otherFilters
        }
      }).catch(() => {
        this.loading = false
        return Promise.reject(false)
      })
    },
    // 获取业务组
    // getBusinessAll() {
    //   return getBusinessAll().then(res => {
    //     this.agentOrgList = res.data
    //   })
    // },
    // select远程搜索
    remoteSearch(v) {
      this.agentList = []
      let f = {}
      // 判断是汉字还是字母
      if (/^[a-zA-Z]+[\d]*$/.test(v)) {
        f = filtersRaw('accountNo', v, 'like')
      } else {
        f = filtersRaw('staffName', v, 'like')
      }
      const data = {
        pageFlag: true,
        filtersRaw: [
          f
        ]
      }
      const id = this.getGroupId()
      if (!id) {
        return
      }
      return getBusinessMembers(pageRequsetBody(data), id).then(res => {
        this.agentList = res.data.records
      })
    },
    // 获取组id
    getGroupId() {
      for (const item of this.groupList) {
        if (item.groupNo === this.formData.group) {
          return item.id
        }
      }
      return ''
    }
  }
}
</script>
<style lang='scss' module>
.msgLog{

}
</style>
